package top.retain;

import java.util.PriorityQueue;

/**
 * @author ivorfan
 * @date 2021/9/10 16:35
 */
public class MidNum {

    public static void main(String[] args) {
        MidNum midNum = new MidNum();
        midNum.addNum(1);
        midNum.addNum(3);
        midNum.addNum(5);
        midNum.addNum(6);
        midNum.addNum(7);
        midNum.addNum(9);
        midNum.addNum(4);
        System.out.println(midNum.findMedian());
    }
    PriorityQueue<Integer> max;
    PriorityQueue<Integer> min;
    /** initialize your data structure here. */
    public MidNum() {
        max = new PriorityQueue<>((o1, o2) -> o2 - o1);
        min = new PriorityQueue<>();
    }

    public void addNum(int num) {
        max.add(num);
        min.add(max.poll());
        if (min.size() > max.size()) {
            max.add(min.poll());
        }
    }

    public double findMedian() {
        if (max.size() == min.size()) {
            return (max.peek() + min.peek()) / 2.0;
        }else {
            return max.peek();
        }
    }
}
